package com.star.robot.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.star.robot.dto.EditTeamRequestDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.dto.TeamRequestFrontDto;
import com.star.robot.entity.*;
import com.star.robot.repository.*;
import com.star.robot.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前端队伍管理
 */
@RestController
@RequestMapping(value = "/team/front")
public class TeamController {

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private CompanyRepository companyRepository;

    @Autowired
    private UserRepositoty userRepositoty;

    @Autowired
    private UserService userService;

    @Autowired
    private TeamMemberRepository teamMemberRepository;

    @Autowired
    private TeamLeaderRepository teamLeaderRepository;

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private ProjectClassRepository projectClassRepository;

    @PostMapping(value = "/addTeam")
    public ResultDto add(@RequestBody EditTeamRequestDto editTeamRequestDto, HttpServletRequest request){
        validateEditTeamRequestDto(editTeamRequestDto);
        Team team = new Team();
        BeanUtils.copyProperties(editTeamRequestDto , team);
        //设置队伍关联的用户
        String phone = userService.getCurrentUsername(request);
        team.setPhone(phone);

        User user=userService.getCurrentUser(request);

        Company company=user.getCompany();

        team.setCompany(company);

        Project project = projectRepository.findLongById(editTeamRequestDto.getProject_id());

        team.setProject(project);

        teamRepository.save(team);

        for (TeamLeader leader : editTeamRequestDto.getLeaders()) {
            leader.setTeam(team);
            teamLeaderRepository.save(leader);
        }

        for (TeamMember member : editTeamRequestDto.getMembers()) {
            member.setTeam(team);
            teamMemberRepository.save(member);
        }

        return ResultDto.builder().success(true).build();
    }

    /**
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/")
    public ResultDto get(HttpServletRequest request){

        String phone = userService.getCurrentUsername(request);
        if(StringUtils.isEmpty(phone)){
            return ResultDto.builder().data(null).build();
        }else{
//            Team team = teamRepository
////                    .getByPhone(phone);
//            List<Team> teams= teamRepository.getListByPhone(phone);
            User user = userService.getCurrentUser(request);
            Company company = user.getCompany();
            List<Team> teams= teamRepository.getListByCompany(company);

            List<Team> reteams=new ArrayList<>();
            for (Team team : teams) {
                //prevent flow
                if(!CollectionUtils.isEmpty(team.getTeamLeaders())){
                    for(TeamLeader teamLeader : team.getTeamLeaders()){
                        teamLeader.setTeam(null);
                    }
                }
                if(!CollectionUtils.isEmpty(team.getTeamMembers())){
                    for(TeamMember teamMember : team.getTeamMembers()){
                        teamMember.setTeam(null);
                    }
                }
                if(!CollectionUtils.isEmpty(team.getTeamScores())){
                    for(TeamScore teamScore : team.getTeamScores()){
                        teamScore.setTeam(null);
                    }
                }



                team.setCompany(company);
                reteams.add(team);
            }

            return  ResultDto.builder().data(reteams).build();
        }
    }

    /**
     * 队伍信息修改front
     * @return
     */
    @PostMapping(value = "/modifyMember")
    @ApiOperation(value = "修改队伍信息",notes = "修改队伍")
    public ResultDto modifyTeam(@RequestBody EditTeamRequestDto editTeamRequestDto) {



        Team team = teamRepository.findById(editTeamRequestDto.getTeamId()).get();
        if (team == null) {
            return ResultDto.builder().success(false).message("查不到队伍信息，请联系管理员").build();
        }

        Date bmEndTime = team.getProject().getBaoMingEndTime();

        if (bmEndTime.before(new Date())) {
            return ResultDto.builder().success(false).message("报名时间已过").build();
        }

        //修改队员
        for (TeamMember member : editTeamRequestDto.getMembers()) {
            //可能有新增队员，所以要判断是否有id。有id修改，无id新增
            if (member.getId() != null) {
            //修改队员

                TeamMember oldmember = teamMemberRepository.findById(member.getId()).get();
                if (oldmember != null) {
                    BeanUtils.copyProperties(member, oldmember);
                    teamMemberRepository.save(oldmember);
                }

            } else {
            //新增队员

                //（市级）
                if (team.getTemplateId() == null ) {
                    //已经确认报名
                    if (team.getConfirmStatus()) {
                        ResultDto.builder().success(false).message("已经确认，不可新增队员").build();
                    }

                }

                //（省级）
                if (team.getTemplateId() != null ) {
                    //已经缴费
                    if (team.getJiaoFei() != null) {
                        ResultDto.builder().success(false).message("已缴费，不可新增队员").build();
                    }

                }

                teamMemberRepository.save(member);

            }

        }

        //修改辅导老师
        for (TeamLeader leader : editTeamRequestDto.getLeaders()) {
            if (leader.getId() != null) {
                TeamLeader oldLeader = teamLeaderRepository.findById(leader.getId()).get();
                if (oldLeader != null) {
                    BeanUtils.copyProperties(leader, oldLeader);
                    teamLeaderRepository.save(oldLeader);
                }
            } else {
                teamLeaderRepository.save(leader);
            }
        }

        return ResultDto.builder().build();
    }

    /**
     * 报名确认（市级队伍使用）
     * @param ids
     * @return
     */
    @GetMapping(value = "/confirm")
    @ApiOperation(value = "报名确认", notes = "报名确认")
    public ResultDto confirm(List<Long> ids) {
        for (Long id : ids) {
            Team team = teamRepository.findById(id).get();
            team.setConfirmStatus(Boolean.TRUE);
            teamRepository.save(team);
        }
        return ResultDto.builder().build();
    }

    /**
     * 查询队伍信息
     * -----------vyanchao
     * @param teamId
     * @return
     */
    @PostMapping(value = "/getTeamById")
    @ApiOperation(value = "查看项目列表",notes = "查看项目列表")
    public ResultDto getTeamById(Long teamId) {
        Team team = teamRepository.findById(teamId).get();

        if(!CollectionUtils.isEmpty(team.getTeamLeaders())){
            for(TeamLeader teamLeader : team.getTeamLeaders()){
                teamLeader.setTeam(null);
            }
        }
        if(!CollectionUtils.isEmpty(team.getTeamMembers())){
            for(TeamMember teamMember : team.getTeamMembers()){
                teamMember.setTeam(null);
            }
        }
        if(!CollectionUtils.isEmpty(team.getTeamScores())){
            for(TeamScore teamScore : team.getTeamScores()){
                teamScore.setTeam(null);
            }
        }

        return  ResultDto.builder().data(team).build();

    }


    /**
     * 查询项目列表
     * -----------vyanchao
     * @return
     */
    @PostMapping(value = "/getProjectList")
    @ApiOperation(value = "查看项目列表",notes = "查看项目列表")
    public ResultDto getProjectList(HttpServletRequest request) {

        User user=userService.getCurrentUser(request);

        List<Project> projects=projectRepository.findByCityId(user.getCityId().longValue());

        return ResultDto.builder().success(true).code(0).message("查询成功").data(projects).build();

    }

    /**
     * 查询项目组别
     * -----------vyanchao
     * @return
     */
    @PostMapping(value = "/getProjectClassList")
    @ApiOperation(value = "组别",notes = "组别")
    public ResultDto getProjectClassList(Long projectId,HttpServletRequest request) {

        List<ProjectClass> list=projectClassRepository.findByProject_Id(projectId);

        for (ProjectClass projectClass : list) {

        }


        return ResultDto.builder().success(true).code(0).message("查询成功").data(list).build();

    }
    /**
     * 删除队员信息
     * -----------vyanchao
     * @return
     */
    @PostMapping(value = "/deleteMember")
    @ApiOperation(value = "删除队员",notes = "删除队员")
    public ResultDto deleteMember(Long id,HttpServletRequest request) {

        if (id != null &&teamMemberRepository.findById(id).get() != null ) {
            teamMemberRepository.deleteById(id);
        }

        return ResultDto.builder().success(true).code(0).message("删除成功").build();

    }
    /**
     * 删除辅导老师信息
     * -----------vyanchao
     * @return
     */
    @PostMapping(value = "/deleteTeacher")
    @ApiOperation(value = "删除辅导老师",notes = "删除辅导老师")
    public ResultDto deleteTeacher(Long id,HttpServletRequest request) {

        if (id != null &&teamLeaderRepository.findById(id) != null) {
            teamLeaderRepository.deleteById(id);
        }

        return ResultDto.builder().success(true).code(0).message("删除成功").build();

    }
    /**
     * 删除队伍信息
     * -----------vyanchao
     * @return
     */
    @PostMapping(value = "/deleteTeam")
    @ApiOperation(value = "删除队伍",notes = "删除队伍")
    public ResultDto deleteTeam(Long id,HttpServletRequest request) {
        //TODO:根据id，删除队伍
//        projectRepository.deleteById(id);
        teamRepository.deleteById(id);
        return ResultDto.builder().success(true).code(0).message("删除成功").build();

    }


    private void validateEditTeamRequestDto(EditTeamRequestDto requestDto) {
//        if(requestDto == null || requestDto.getId() != null){
//            throw new IllegalArgumentException("添加队伍失败,参数校验异常");
//        }

        if(requestDto.getProjectClassEnum() == null){
            throw new IllegalArgumentException("添加队伍失败,组别必填");
        }
        if(StringUtils.isEmpty(requestDto.getTeamName())){
            throw new IllegalArgumentException("添加队伍失败,队名必填");
        }
        if(CollectionUtils.isEmpty(requestDto.getMembers())){
            throw new IllegalArgumentException("添加队伍失败,队员至少一个");
        }
        if(CollectionUtils.isEmpty(requestDto.getLeaders())){
            throw new IllegalArgumentException("添加队伍失败,辅导老师至少一个");
        }
    }

    private void validateRequestParam(TeamRequestFrontDto requestDto) {
        if(requestDto == null || requestDto.getId() != null){
            throw new IllegalArgumentException("添加队伍失败,参数校验异常");
        }

        if(requestDto.getProjectClassEnum() == null){
            throw new IllegalArgumentException("添加队伍失败,组别必填");
        }
        if(StringUtils.isEmpty(requestDto.getTeamName())){
            throw new IllegalArgumentException("添加队伍失败,队名必填");
        }
        if(CollectionUtils.isEmpty(requestDto.getTeamMembers())){
            throw new IllegalArgumentException("添加队伍失败,队员至少一个");
        }
        if(CollectionUtils.isEmpty(requestDto.getTeamLeaders())){
            throw new IllegalArgumentException("添加队伍失败,辅导老师至少一个");
        }
    }
}
